介紹
代理模式對目標物件提供額外的存取限制。
C++範例
#include <iostream>
#include <memory>
class IWeapon
{
public:
virtual ~IWeapon()
{
std::cout << "IWeapon destructor called" << std::endl;
}
virtual void Equip() = 0;
};
class KingSword : public IWeapon
{
public:
void Equip() override
{
std::cout << "King sword equipped" << std::endl;
}
};
class KingSwordProxy : public IWeapon
{
public:
KingSwordProxy(int playerLevel) :
m_PlayerLevel(playerLevel),
m_Weapon(std::make_unique<KingSword>())
{
}
void Equip() override
{
if (m_PlayerLevel >= 30)
{
m_Weapon->Equip();
}
else
{
std::cout << "You need to reach level 30 to use this weapon" << std::endl;
}
}
private:
int m_PlayerLevel;
std::unique_ptr<IWeapon> m_Weapon;
};
int main()
{
// Player is level 23
std::unique_ptr<IWeapon> weapon = std::make_unique<KingSwordProxy>(23);
weapon->Equip();
// Player is level 30
weapon = std::make_unique<KingSwordProxy>(30);
weapon->Equip();
return 0;
}
Output:
You need to reach level 30 to use this weapon
IWeapon destructor called
IWeapon destructor called
King sword equipped
IWeapon destructor called
IWeapon destructor called